﻿using System;
using System.Collections.Generic;
using AccessControl.Contracts.Video;
using AccessControl.Video.Rtsp;
using System.Net;

namespace AccessControl.Video
{
	public class VideoPlayer : IVideoPlayer
	{
		#region Fields

		RtspClient _rtspClient;

		#endregion

		#region IVideoPlayer Members

		public bool RequestStartVideo(IPAddress ip, int portNumber)
		{
			_rtspClient = new RtspClient()
			{
				IP = ip,
				PortNumber = portNumber
			};

			_rtspClient.Initialized += (OnInitialized);
			_rtspClient.NewFrame += (OnNewFrame);
			_rtspClient.Terminated += (OnTerminated);

			return _rtspClient.Initialize();
		}

		public bool RequestStopVideo()
		{
			if (_rtspClient != null)
				return _rtspClient.Terminate();

			return false;
		}

		public event VideoEventHandler VideoStarted;

		public event VideoEventHandler VideoStopped;

		public event NewFrameEventHandler NewFrame;

		#endregion

		#region Private Members

		void OnNewFrame(byte[] frameBytes, DateTime timeStamp, int width, int height)
		{
			if (NewFrame != null)
				NewFrame(frameBytes, timeStamp, width, height);
		}

		private void OnInitialized(bool bSuccess)
		{
			if (VideoStarted != null)
				VideoStarted(bSuccess);
		}

		private void OnTerminated(bool bSuccess)
		{
			if (VideoStopped != null)
				VideoStopped(bSuccess);
		}

		#endregion
	}
}
